<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>公共法律知识题库</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css">
    <style>
        /* :root {
            --primary-color: #1a56db;
            --secondary-color: #0f3a8c;
            --light-bg: #f3f4f6;
            --card-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        } */

        :root {
            --primary-color: #2486b9;
            --secondary-color: #006192;
            --light-bg: #f3f4f6;
            --card-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        body {
            background-color: #f5f7fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            color: #333;
            padding-bottom: 100px;
        }

        .navbar {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .header-title {
            font-weight: 700;
            color: white;
        }

        .search-container {
            background-color: white;
            border-radius: 12px;
            padding: 25px;
            box-shadow: var(--card-shadow);
            margin-top: -30px;
            position: relative;
            z-index: 10;
        }

        .search-btn {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            font-weight: 600;
        }

        .search-btn:disabled {
            opacity: 0.7;
            cursor: not-allowed;
        }

        .question-card {
            background-color: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: var(--card-shadow);
            transition: transform 0.3s ease;
        }

        .question-card:hover {
            transform: translateY(-5px);
        }

        .question-title {
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 15px;
        }

        .options-list {
            list-style-type: none;
            padding: 0;
        }

        .options-list li {
            padding: 8px 12px;
            margin-bottom: 8px;
            background-color: var(--light-bg);
            border-radius: 6px;
            border-left: 4px solid var(--primary-color);
        }

        .correct-answer {
            background-color: #d1fae5 !important;
            border-left: 4px solid #10b981 !important;
            font-weight: 600;
        }

        .pagination {
            margin-top: 30px;
        }

        .page-item.active .page-link {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .page-link {
            color: var(--primary-color);
            cursor: pointer;
        }

        .results-count {
            color: #6b7280;
            font-size: 0.9rem;
        }

        .type-badge {
            background-color: var(--primary-color);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
            margin-left: 10px;
            display: flex;
            align-items: center;
        }

        .type-badge i {
            margin-right: 4px;
        }

        .bank-info {
            color: #6b7280;
            font-size: 0.85rem;
            margin-top: 5px;
        }

        .answer-info {
            color: #10b981;
            font-size: 0.85rem;
            margin-top: 5px;
            font-weight: 600;
        }

        .footer {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 15px 0;
            text-align: center;
            position: fixed;
            bottom: 0;
            width: 100%;
        }

        .no-results {
            text-align: center;
            padding: 40px 0;
            color: #6b7280;
        }

        .no-results i {
            font-size: 3rem;
            margin-bottom: 15px;
            color: #9ca3af;
        }

        .loading-spinner {
            display: none;
            text-align: center;
            padding: 30px 0;
        }

        .spinner-border {
            width: 3rem;
            height: 3rem;
            color: var(--primary-color);
        }

        .pagination-info {
            text-align: center;
            margin-top: 15px;
            color: #6b7280;
            font-size: 0.9rem;
        }

        .load-more-container {
            text-align: center;
            margin-top: 20px;
            margin-bottom: 40px;
        }

        .load-more-btn {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            border: none;
            padding: 10px 25px;
            border-radius: 8px;
            font-weight: 600;
        }

        .load-more-btn:disabled {
            opacity: 0.7;
            cursor: not-allowed;
        }
    </style>
</head>

<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container">
            <a class="navbar-brand" href="#">
                <i class="bi bi-journal-bookmark-fill me-2"></i>
                <span class="header-title">公共法律知识题库</span>
            </a>
        </div>
    </nav>

    <div class="container mt-4">
        <!-- 搜索区域 -->
        <div class="search-container">
            <div class="row">
                <div class="col-md-10">
                    <div class="form-group">
                        <label for="searchInput" class="form-label">搜索题目</label>
                        <input type="text" class="form-control" id="searchInput" placeholder="输入题目关键词...">
                    </div>
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button class="btn search-btn w-100" id="searchBtn">
                        <i class="bi bi-search me-1"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- 加载指示器 -->
        <div class="loading-spinner" id="loadingSpinner">
            <div class="spinner-border" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2">正在加载试题，请稍候...</p>
        </div>

        <!-- 结果统计 -->
        <div class="d-flex justify-content-between align-items-center mt-4 mb-3">
            <h5 class="m-0">查询结果</h5>
            <span class="results-count" id="resultsCount">显示 0 条结果</span>
        </div>

        <!-- 试题列表 -->
        <div id="questionsContainer">
            <!-- 试题将通过JavaScript动态加载 -->
        </div>

        <!-- 加载更多按钮 -->
        <div class="load-more-container" id="loadMoreContainer" style="display: none;">
            <button class="load-more-btn" id="loadMoreBtn">
                <i class="bi bi-arrow-down-circle me-1"></i> 加载更多
            </button>
        </div>

        <!-- 分页控件 -->
        <nav aria-label="Page navigation">
            <ul class="pagination justify-content-center" id="pagination">
                <!-- 分页将通过JavaScript动态生成 -->
            </ul>
        </nav>

        <!-- 分页信息 -->
        <div class="pagination-info" id="paginationInfo">
            第 0 页，共 0 页，每页 0 条
        </div>
    </div>

    <!-- 页脚 -->
    <div class="footer">
        <div class="container">
            <span>© 2025 技术支持 Yingke - 仅供学习使用</span>
        </div>
    </div>

    <script>
        // 使用IIFE封装代码，避免全局污染
        (function () {
            // 全局变量
            let currentPage = 1;
            let currentSearchTerm = '';
            let paginationData = {
                page: 1,
                pageSize: 10,
                totalPages: 0,
                totalRecords: 0
            };

            // DOM元素
            const searchInput = document.getElementById('searchInput');
            const searchBtn = document.getElementById('searchBtn');
            const questionsContainer = document.getElementById('questionsContainer');
            const pagination = document.getElementById('pagination');
            const resultsCount = document.getElementById('resultsCount');
            const loadingSpinner = document.getElementById('loadingSpinner');
            const paginationInfo = document.getElementById('paginationInfo');
            const loadMoreContainer = document.getElementById('loadMoreContainer');
            const loadMoreBtn = document.getElementById('loadMoreBtn');

            // 初始化
            document.addEventListener('DOMContentLoaded', function () {
                // 默认加载第一页题目
                fetchQuestions(1, '', false);

                // 添加事件监听器
                searchBtn.addEventListener('click', performSearch);
                searchInput.addEventListener('keypress', function (e) {
                    if (e.key === 'Enter') {
                        performSearch();
                    }
                });

                // 加载更多按钮事件
                loadMoreBtn.addEventListener('click', loadMoreQuestions);

                // 使用事件委托处理分页点击
                pagination.addEventListener('click', function (e) {
                    if (e.target.classList.contains('page-link') && !e.target.parentElement.classList.contains('disabled')) {
                        e.preventDefault();
                        const targetPage = parseInt(e.target.dataset.page);
                        if (!isNaN(targetPage)) {
                            changePage(targetPage);
                        }
                    }
                });
            });

            // 执行搜索
            function performSearch() {
                const searchTerm = searchInput.value.trim();
                currentSearchTerm = searchTerm;
                currentPage = 1;
                fetchQuestions(currentPage, searchTerm, false);
            }

            // 加载更多题目
            function loadMoreQuestions() {
                currentPage++;
                fetchQuestions(currentPage, currentSearchTerm, true);
            }

            // 从API获取题目
            async function fetchQuestions(page, title, append) {
                // 禁用搜索按钮，防止重复请求
                searchBtn.disabled = true;
                searchBtn.innerHTML = '<i class="bi bi-search me-1"></i> 搜索中...';

                // 显示加载指示器
                if (!append) {
                    loadingSpinner.style.display = 'block';
                    questionsContainer.innerHTML = '';
                    pagination.innerHTML = '';
                    paginationInfo.textContent = '加载中...';
                    loadMoreContainer.style.display = 'none';
                } else {
                    loadMoreBtn.disabled = true;
                    loadMoreBtn.innerHTML = '<i class="bi bi-arrow-repeat me-1"></i> 加载中...';
                }

                try {
                    // 构建请求URL
                    const apiUrl = `https://gox9vh.laf.run/chaxun?page=${page}&title=${encodeURIComponent(title)}`;

                    // 发送请求
                    const response = await fetch(apiUrl);
                    if (!response.ok) {
                        throw new Error(`HTTP错误! 状态: ${response.status}`);
                    }

                    const data = await response.json();

                    // 隐藏加载指示器
                    loadingSpinner.style.display = 'none';

                    // 处理返回的数据
                    if (data && data.data) {
                        // 保存分页信息 - 根据实际返回的数据格式调整
                        if (data.page) paginationData.page = data.page;
                        if (data.pageSize) paginationData.pageSize = data.pageSize;
                        if (data.total) paginationData.totalPages = data.total; // 总页数

                        // 计算总记录数
                        if (data.data.length > 0) {
                            paginationData.totalRecords = (paginationData.page - 1) * paginationData.pageSize + data.data.length;
                        }

                        if (append) {
                            appendQuestions(data.data);
                        } else {
                            displayQuestions(data.data);
                        }
                        updatePagination();
                        updateResultsCount();
                        updatePaginationInfo();

                        // 显示或隐藏加载更多按钮
                        if (paginationData.page < paginationData.totalPages) {
                            loadMoreContainer.style.display = 'block';
                        } else {
                            loadMoreContainer.style.display = 'none';
                        }
                    } else {
                        if (!append) {
                            showNoResults();
                            resetPaginationInfo();
                        }
                    }
                } catch (error) {
                    console.error('获取试题时出错:', error);
                    loadingSpinner.style.display = 'none';
                    if (!append) {
                        questionsContainer.innerHTML = `
                            <div class="alert alert-danger" role="alert">
                                <i class="bi bi-exclamation-triangle-fill"></i> 获取试题时出错，请稍后重试。
                            </div>
                        `;
                        resetPaginationInfo();
                    }
                } finally {
                    // 重新启用搜索按钮
                    searchBtn.disabled = false;
                    searchBtn.innerHTML = '<i class="bi bi-search me-1"></i> 搜索';

                    // 重新启用加载更多按钮
                    loadMoreBtn.disabled = false;
                    loadMoreBtn.innerHTML = '<i class="bi bi-arrow-down-circle me-1"></i> 加载更多';
                }
            }

            // 显示题目
            function displayQuestions(questions) {
                // 清空容器
                questionsContainer.innerHTML = '';

                if (!questions || questions.length === 0) {
                    showNoResults();
                    return;
                }

                // 添加题目到容器
                questions.forEach(question => {
                    const questionElement = createQuestionElement(question);
                    questionsContainer.appendChild(questionElement);
                });
            }

            // 追加题目
            function appendQuestions(questions) {
                if (!questions || questions.length === 0) {
                    return;
                }

                // 添加题目到容器
                questions.forEach(question => {
                    const questionElement = createQuestionElement(question);
                    questionsContainer.appendChild(questionElement);
                });
            }

            // 创建题目元素
            function createQuestionElement(question) {
                const div = document.createElement('div');
                div.className = 'question-card';

                // 题型显示和图标
                let typeText = '';
                let typeIcon = '';

                if (question.type === 'single_choice') {
                    typeText = '单';
                    //typeIcon = '<i class="bi bi-ui-radios"></i>';
                } else if (question.type === 'multiple_choice') {
                    typeText = '多';
                    // typeIcon = '<i class="bi bi-ui-checks"></i>';
                } else if (question.type === 'true_false') {
                    typeText = '判';
                    // typeIcon = '<i class="bi bi-check2-circle"></i>';
                } else {
                    typeText = question.type;
                    typeIcon = '<i class="bi bi-question-circle"></i>';
                }

                // 转义HTML内容，防止XSS攻击
                const escapedTitle = escapeHtml(question.title || '无题目内容');
                const escapedBank = escapeHtml(question.bank || '未知题库');

                // 处理答案显示
                let answerDisplay = '';
                if (question.answer) {
                    if (Array.isArray(question.answer)) {
                        answerDisplay = question.answer.join(', ');
                    } else {
                        answerDisplay = question.answer;
                    }
                }

                // 选项HTML
                let optionsHtml = '';
                if (question.options && Array.isArray(question.options)) {
                    question.options.forEach(option => {
                        let isCorrect = false;

                        // 处理多选题答案格式（如["AC"]）
                        if (question.type === 'multiple_choice' && question.answer) {
                            let correctAnswers = [];

                            // 处理数组格式的答案
                            if (Array.isArray(question.answer)) {
                                // 如果数组元素是字符串（如["AC"]）
                                if (typeof question.answer[0] === 'string') {
                                    correctAnswers = question.answer[0].split('');
                                } else {
                                    // 其他格式暂不处理
                                    correctAnswers = [];
                                }
                            } else if (typeof question.answer === 'string') {
                                // 处理字符串格式的答案
                                correctAnswers = question.answer.split('');
                            }

                            isCorrect = correctAnswers.includes(option.key);
                        } else {
                            // 单选题和判断题
                            isCorrect = question.answer && question.answer.includes(option.key);
                        }

                        // 转义选项内容
                        const escapedValue = escapeHtml(option.value);
                        optionsHtml += `
                            <li class="${isCorrect ? 'correct-answer' : ''}">
                                ${option.key}. ${escapedValue}
                            </li>
                        `;
                    });
                }

                div.innerHTML = `
                    <div class="d-flex justify-content-between align-items-start">
                        <h6 class="question-title">${escapedTitle}</h6>
                        <span class="type-badge">${typeIcon} ${typeText}</span>
                    </div>
                    <ul class="options-list">
                        ${optionsHtml}
                    </ul>
                    <div class="bank-info">来源: ${escapedBank}</div>
                    <div class="answer-info">答案: ${answerDisplay}</div>
                `;

                return div;
            }

            // HTML转义函数，防止XSS攻击
            function escapeHtml(unsafe) {
                if (!unsafe) return '';
                return unsafe
                    .replace(/&/g, "&amp;")
                    .replace(/</g, "&lt;")
                    .replace(/>/g, "&gt;")
                    .replace(/"/g, "&quot;")
                    .replace(/'/g, "&#039;");
            }

            // 显示无结果消息
            function showNoResults() {
                questionsContainer.innerHTML = `
                    <div class="no-results">
                        <i class="bi bi-search"></i>
                        <h5>没有找到相关题目</h5>
                        <p>请尝试其他搜索关键词</p>
                    </div>
                `;
            }

            // 更新分页控件
            function updatePagination() {
                const totalPages = paginationData.totalPages;
                const currentPage = paginationData.page;

                // 清空分页控件
                pagination.innerHTML = '';

                if (totalPages <= 1) {
                    return;
                }

                // 添加上一页按钮
                const prevLi = document.createElement('li');
                prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
                prevLi.innerHTML = `<a class="page-link" href="#" aria-label="Previous" data-page="${currentPage - 1}">
                    <span aria-hidden="true">&laquo;</span> 上一页
                </a>`;
                pagination.appendChild(prevLi);

                // 计算显示的页码范围
                let startPage = Math.max(1, currentPage - 2);
                let endPage = Math.min(totalPages, currentPage + 2);

                // 确保显示5个页码，如果不足5个，则调整范围
                if (endPage - startPage < 4) {
                    if (startPage === 1) {
                        endPage = Math.min(startPage + 4, totalPages);
                    } else if (endPage === totalPages) {
                        startPage = Math.max(1, endPage - 4);
                    }
                }

                // 添加第一页
                if (startPage > 1) {
                    const firstLi = document.createElement('li');
                    firstLi.className = 'page-item';
                    firstLi.innerHTML = `<a class="page-link" href="#" data-page="1">1</a>`;
                    pagination.appendChild(firstLi);

                    if (startPage > 2) {
                        const ellipsisLi = document.createElement('li');
                        ellipsisLi.className = 'page-item disabled';
                        ellipsisLi.innerHTML = `<span class="page-link">...</span>`;
                        pagination.appendChild(ellipsisLi);
                    }
                }

                // 添加页码按钮
                for (let i = startPage; i <= endPage; i++) {
                    const li = document.createElement('li');
                    li.className = `page-item ${i === currentPage ? 'active' : ''}`;
                    li.innerHTML = `<a class="page-link" href="#" data-page="${i}">${i}</a>`;
                    pagination.appendChild(li);
                }

                // 添加最后一页
                if (endPage < totalPages) {
                    if (endPage < totalPages - 1) {
                        const ellipsisLi = document.createElement('li');
                        ellipsisLi.className = 'page-item disabled';
                        ellipsisLi.innerHTML = `<span class="page-link">...</span>`;
                        pagination.appendChild(ellipsisLi);
                    }

                    const lastLi = document.createElement('li');
                    lastLi.className = 'page-item';
                    lastLi.innerHTML = `<a class="page-link" href="#" data-page="${totalPages}">${totalPages}</a>`;
                    pagination.appendChild(lastLi);
                }

                // 添加下一页按钮
                const nextLi = document.createElement('li');
                nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
                nextLi.innerHTML = `<a class="page-link" href="#" aria-label="Next" data-page="${currentPage + 1}">
                    下一页 <span aria-hidden="true">&raquo;</span>
                </a>`;
                pagination.appendChild(nextLi);
            }

            // 更改页面
            function changePage(page) {
                if (page < 1 || page > paginationData.totalPages) return;

                currentPage = page;
                fetchQuestions(currentPage, currentSearchTerm, false);

                // 滚动到顶部
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }

            // 更新结果计数
            function updateResultsCount() {
                const startIndex = (paginationData.page - 1) * paginationData.pageSize + 1;
                const endIndex = Math.min(paginationData.page * paginationData.pageSize, paginationData.totalRecords);

                resultsCount.textContent = `显示 ${startIndex}-${endIndex} 条，共 ${paginationData.totalPages} 页`;
            }

            // 更新分页信息
            function updatePaginationInfo() {
                paginationInfo.textContent = `第 ${paginationData.page} 页，共 ${paginationData.totalPages} 页，每页 ${paginationData.pageSize} 条`;
            }

            // 重置分页信息
            function resetPaginationInfo() {
                paginationInfo.textContent = "暂无数据";
            }

            // 暴露必要函数到全局作用域
            window.changePage = changePage;
        })();
    </script>
</body>

</html>